import React from "react";
import RcDropdown from "rc-dropdown";
import { Close, CaretDown, Datecalender } from "@ct0/icons";
import { isEmpty } from "@ct0/functions";
import classNames from "classnames";
import { useDropdownStyles } from "./styles";

const TRIGGER = ["click"];

const defaultPopupContainer = (node: any) => node.parentElement;

export default function Dropdown({
  visible,
  overlay,
  label,
  valueCount,
  valueLabel,
  shadow,
  style,
  icon,
  onVisibleChange,
  onClear,
  emptyLabel = "全部",
  getPopupContainer = defaultPopupContainer,
}: {
  visible: boolean;
  shadow?: boolean;
  overlay: React.ReactElement;
  valueLabel?: string;
  valueCount?: number;
  label: string;
  style?: React.CSSProperties;
  icon?: string;
  onVisibleChange: (visible: boolean) => void;
  onClear: () => void;
  emptyLabel?: string;
  getPopupContainer?: (node: HTMLElement) => HTMLElement;
}) {
  const classes = useDropdownStyles();

  return (
    <div className={classes.item}>
      <RcDropdown
        visible={visible}
        prefixCls="ct0-quickfilter-dropdown"
        trigger={TRIGGER}
        onVisibleChange={onVisibleChange}
        overlay={visible ? overlay : <div />}
        getPopupContainer={getPopupContainer}
      >
        <div
          style={style}
          className={classNames(
            classes.itemLabel,
            shadow ? classes.itemShadow : classes.itemBorder
          )}
        >
          <div
            className={classNames(
              classes.labelText,
              valueLabel && classes.blueText
            )}
          >
            {label && label + ": "}
          </div>
          {isEmpty(valueLabel) ? (
            <div>{emptyLabel}</div>
          ) : (
            <div className={classNames(classes.valueText, classes.blueText)}>
              {valueLabel}
            </div>
          )}
          {Number(valueCount) > 1 && (
            <span className={classes.valueCount}>{valueCount}</span>
          )}
          <div className={classes.flexGrow} />
          {isEmpty(valueLabel) ? (
            icon == "calendar" ? (
              <Datecalender className={classes.calendarIcon} />
            ) : (
              <CaretDown className={classes.caretDownIcon} />
            )
          ) : (
            <div
              onClick={(e) => {
                e.stopPropagation();
                onClear();
              }}
              className={classNames(
                classes.closeIcon,
                valueLabel && classes.blueText
              )}
            >
              <Close />
            </div>
          )}
        </div>
      </RcDropdown>
    </div>
  );
}
